package com.archetypus.projectschedule.web.common.cmd;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.archetypus.projectschedule.common.AlternateResource;
import com.archetypus.projectschedule.common.Resource;
import com.archetypus.projectschedule.common.ResourcesTable;
import com.archetypus.projectschedule.common.exceptions.ProjectSchedulerException;

public class FrontController extends HttpServlet {

	private static final long serialVersionUID = -8124283925336449112L;

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String resourceKey = null;
		try {
			// Obtener la clave asociada a la peticion.
			String uri = request.getRequestURI();
			resourceKey = uri.substring(uri.lastIndexOf("/") + 1, uri
					.lastIndexOf("."));

			/**
			 * Obtener el recurso solicitado y despachar la peticion. Se enlazan
			 * peticiones segun lo indique el ActionFlow.xml
			 */
			boolean procesar = true;
			int order = 1;
			Resource resourceView = null;
			while (procesar) {
				// Recurso a procesar
				Resource resource = ResourcesTable.getInstance().getResource(
						resourceKey + "." + order);

				if (resource != null && resource.isCommand()) {
					// Command a ejecutar
					ICommand cmd = (ICommand) Class.forName(resource.getPath())
							.newInstance();
					cmd.execute(request, response);
				} else {
					procesar = false;
					resourceView = resource;
				}
				order++;

				AlternateResource alternateResource = (AlternateResource) request
						.getAttribute("alternateResource");
				if (alternateResource != null
						&& alternateResource.isActivateAltFlow()) {
					resourceKey += "." + alternateResource.getAltFlowId();
					order = 1;
					request.removeAttribute("alternateResource");
				}
			}

			request.getRequestDispatcher(resourceView.getPath()).forward(
					request, response);

		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof ProjectSchedulerException) {
				request.setAttribute("error", (ProjectSchedulerException) e);
			} else {
				request.setAttribute("error", new ProjectSchedulerException(
						"Error procesing the request " + resourceKey,e));
			}

			request.getRequestDispatcher("/generic/error.jsp").forward(request,
					response);
		}

	}
}
